package com.linlang.grasharepro.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.linlang.grasharepro.R;
import com.linlang.grasharepro.dao.UserDB;
import com.linlang.grasharepro.model.User;

import java.util.ArrayList;

/**
 * Created by lixin on 2016-8-8.
 */
public class LoginActivity extends Activity {
    private UserDB userDB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {

    }

    public void login(View view){
//        Intent intent = new Intent(LoginActivity.this,
//                    MainActivity.class);
//            startActivity(intent);
//            finish();
        userDB = new UserDB(this);
        userDB.open();

        EditText et_loginName = (EditText) findViewById(R.id.et_loginId);
        String loginName = et_loginName.getText().toString().trim();
        EditText et_password = (EditText) findViewById(R.id.et_password);
        String password = et_password.getText().toString().trim();
        User user = new User();
        user.setLoginName(loginName);
        user.setLoginPass(password);
        ArrayList<User> isLogin = userDB.login(user);

        Log.d("loginName:",loginName);
        Log.d("password:",password);

        if(isLogin.size() != 0){
            //保存登陆信息到本地
            SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
            editor.putString("id",isLogin.get(0).get_Id());
            editor.putString("account", loginName);
            editor.putString("password", password);
            editor.putString("type", isLogin.get(0).getRole());
            editor.putString("major", isLogin.get(0).getMajor());
            editor.putString("headUrl", isLogin.get(0).getHeadUrl());
            editor.putString("academicStarts", isLogin.get(0).getAcademicStarts());
            editor.putString("introduction", isLogin.get(0).getIntroduction());
            editor.putString("sex", isLogin.get(0).getSex());
            editor.commit();//提交修改

            Intent intent = new Intent(LoginActivity.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }else{
            Toast.makeText(LoginActivity.this, "登陆失败，用户名或密码错误", Toast.LENGTH_LONG).show();
        }
    }

    public void regist(View view){
        Intent intent = new Intent(LoginActivity.this,
                RegistActivity.class);
        startActivity(intent);
    }

}
